<template>
	<view class="input-box">
		<picker :disabled="disabled" mode="multiSelector" @change="MultiChange" @columnchange="MultiColumnChange" :range="multiArray" range-key="label" :value="defaultValue">
			<view class="picker" :class="disabled ? 'text-grey' : ''">
				<text class="text-grey text-sm" v-if="!chooseObj.value">请选择</text>
				{{ chooseObj.label }}&nbsp;
			</view>
		</picker>
	</view>
</template>
<script>
import dayjs from 'dayjs';
import isoWeek from 'dayjs/plugin/isoWeek';
import isoWeeksInYear from 'dayjs/plugin/isoWeeksInYear';
import isLeapYear from 'dayjs/plugin/isLeapYear';
dayjs.extend(isoWeeksInYear);
dayjs.extend(isLeapYear);
dayjs.extend(isoWeek);
const now = dayjs();

export default {
	props: {
		// 绑定值，可以是主键ID或者对象（对象至少需要包含主键id，如果包含了id，fullName则程序会减少一步找数据时间）
		modelValue: {
			type: [Object, String],
			default() {
				return '';
			}
		},
		// 禁用
		disabled: {
			type: Boolean,
			default() {
				return false;
			}
		}
	},
	emits: ['update:modelValue', 'change'],
	watch: {
		modelValue: {
			handler(val, oldVal) {
				if (!val) {
					return;
				}
				if (val === this.chooseObj) {
					return;
				}
				if (typeof val === 'string' || (typeof val === 'object' && typeof val.value === 'string')) {
					let sArray = [];
					if (typeof val === 'string') {
						sArray = val.split('-');
					} else if (typeof val === 'object' && typeof val.value === 'string') {
						sArray = val.value.split('-');
					} else {
						return;
					}

					const d = dayjs().year(sArray[0]);
					const weekDay = d.isoWeek(sArray[1]);
					const dayInWeek = weekDay.isoWeekday(); //本周第几天
					// 一周的开始日期
					const weekDayStart = weekDay.subtract(dayInWeek - 1, 'day');
					// 一周的结束日期
					const weekDayEnd = weekDay.add(7 - dayInWeek, 'day');

					this.chooseObj = {
						label: `${weekDay.year()}年第${weekDay.isoWeek()}周(${dayjs(weekDayStart).format('MM-DD')}至${dayjs(weekDayEnd).format('MM-DD')})`,
						value: `${weekDay.year()}-${weekDay.isoWeek()}`,
						year: weekDay.year(),
						week: weekDay.isoWeek(),
						weekDayStart: weekDayStart.format('MM-DD'),
						weekDayEnd: weekDayEnd.format('MM-DD')
					};
					return;
				}
				if (val.weekDayStart && val.weekDayEnd) {
					const weekDay = dayjs(val.weekDayStart);
					this.chooseObj = {
						label: `${weekDay.year()}年第${weekDay.isoWeek()}周(${dayjs(val.weekDayStart).format('MM-DD')}至${dayjs(val.weekDayEnd).format('MM-DD')})`,
						value: `${weekDay.year()}-${weekDay.isoWeek()}`,
						year: weekDay.year(),
						week: weekDay.isoWeek(),
						weekDayStart: val.weekDayStart,
						weekDayEnd: val.weekDayEnd
					};
				}
			},
			immediate: true
		}
	},
	data() {
		return {
			multiArray: [],
			index: 0,
			multiIndex: 0,
			chooseObj: {},
			defaultValue: []
		};
	},
	created() {
		this.multiArray = [];
		this.loadData(now.year());
	},
	methods: {
		MultiChange(e) {
			const { value } = e.detail;

			const chooseValue = [];
			for (var i = 0; i < value.length; i++) {
				chooseValue.push(this.multiArray[i][value[i]]);
			}
			const thatYear = now.year(chooseValue[0].value);
			const weekday = thatYear.isoWeekday(); //本周第几天
			// 一周中今天的日期
			const weekDayNow = thatYear.isoWeek(chooseValue[1].value);
			// 一周的开始日期
			const weekDayStart = weekDayNow.subtract(weekday - 1, 'day');
			// 一周的结束日期
			const weekDayEnd = weekDayNow.add(7 - weekday, 'day');
			this.chooseObj = {
				label: `${chooseValue[0].label}年${chooseValue[1].label}`,
				value: `${chooseValue[0].value}-${chooseValue[1].value}`,
				year: chooseValue[0].value,
				week: chooseValue[1].value,
				weekDayStart: weekDayStart.format('YYYY-MM-DD'),
				weekDayEnd: weekDayEnd.format('YYYY-MM-DD')
			};
			this.$emit('update:modelValue', this.chooseObj);
			this.$emit('change', this.chooseObj);
		},
		MultiColumnChange(e) {
			const { column, value } = e.detail;
			const chooseObj = this.multiArray[column][value];
			if (this.multiArray.length > column + 1) {
				// 说明还有下级数据，需要刷新下级数据
				for (var i = 0; i < this.multiArray.length - (column + 1); i++) {
					this.multiArray.pop();
				}
				this.createWeekArray(chooseObj.value);
			}
		},

		loadData(year) {
			this.createYearArray(year);
			this.createWeekArray(year);
			const weekNum = now.isoWeek(); //本周是第几周
			this.defaultValue.push(50, weekNum - 1);
		},
		/**
		 * 创建年数组，上下50年
		 */
		createYearArray(nowYear) {
			const array = [];
			for (var i = nowYear - 50; i <= nowYear + 50; i++) {
				array.push({
					label: i,
					value: i
				});
			}
			this.multiArray.push(array);
		},
		/**
		 * 创建周数组
		 */
		createWeekArray(nowYear) {
			const thatYear = now.year(nowYear);
			const weeksInYear = thatYear.isoWeeksInYear(); //一年的周数
			const weekday = thatYear.isoWeekday(); //本周第几天
			const array = [];
			for (var i = 1; i <= weeksInYear; i++) {
				// 一周中今天的日期
				const weekDayNow = thatYear.isoWeek(i);
				// 一周的开始日期
				const weekDayStart = weekDayNow.subtract(weekday - 1, 'day');
				// 一周的结束日期
				const weekDayEnd = weekDayNow.add(7 - weekday, 'day');
				array.push({
					label: `第${i}周(${weekDayStart.format('MM-DD')}至${weekDayEnd.format('MM-DD')})`,
					value: i
				});
			}
			this.multiArray.push(array);
		}
	}
};
</script>
<style scoped>
.input-box {
	position: relative;
	overflow: hidden;
	flex: 1;
	line-height: 1;
	font-size: 14px;
	flex-direction: row;
	align-items: center;
	border: 1px solid #dcdfe6;
	border-radius: 4px;
	padding: 12px 15px;
}
.text-grey {
	color: #999;
}
</style>
